package com.yishun.springboot.shiroconfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.yishun.springboot.mapper.RoleMapper;

@Configuration
public class ShiroConfig {

	@Resource
	RoleMapper roleDao;

	// 自定义Realm
	@Bean
	public MyRealm getMyRealm() {
		MyRealm myRealm = new MyRealm();
		return myRealm;
	}

	// SecurityManager安全管理器
	@Bean
	public DefaultWebSecurityManager getDefaultWebSecurityManager(MyRealm myRealm) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		// securityManager要完成校验，需要realm
		securityManager.setRealm(myRealm);
		return securityManager;
	}

	// 过滤器
	@Bean
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
		ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
		filter.setSecurityManager(defaultWebSecurityManager);
		// 设置shiro的拦截规则
		// anon 匿名用户可访问 authc 认证用户可访问
		// user 使用RemeberMe的用户可访问 perms 对应权限可访问
		// role 对应的角色可访问

		Map<String, String> filterMap = new HashMap<>();
		List<Map<String, Object>> list = roleDao.getRoleAndInterface();
		filterMap.put("/", "anon");
		String val = "";
		for (Map<String, Object> map : list) {
			if (map.get("role_or_perms").toString() != null) {
				val = map.get("role_or_perms").toString();
			}
			filterMap.put(map.get("interface_name").toString(), map.get("authority_level").toString() + val);
		}
		filterMap.put("/**", "authc");
		filter.setFilterChainDefinitionMap(filterMap);

		filter.setLoginUrl("/www.baidu.com");
		// 设置未授权页面跳转到登录页面
		filter.setUnauthorizedUrl("/login.html");
		return filter;
	}

}
